package com.dayi.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.dayi.R;
import com.dayi.R2;
import com.dayi.bean.StudentCancelQuestionBean;
import com.dayi.bean.StudentWaitDataBean;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.utils.time_deal.TimeUtils;
import com.lib.fastkit.utils.timer_countdown.CountDownTimer;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.observer.ObserverListener;
import com.lib.observer.ObserverManager;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.utls.glide.GlideConfig;
import com.lib.view.navigationbar.NomalNavigationBar;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

@Route(path = ARouterPathUtils.Tablet_DaYi_StudentConnectWaitActivity)
public class StudentConnectWaitActivity extends BaseAppActivity implements ObserverListener {

    @BindView(R2.id.iv_gif)
    ImageView ivGif;
    @BindView(R2.id.tv_cut_time)
    TextView tvCutTime;
    @BindView(R2.id.btn_back)
    Button btnBack;
    @BindView(R2.id.btn_share)
    Button btnShare;
    @BindView(R2.id.tv_time)
    TextView tvTime;
    @BindView(R2.id.rv)
    RecyclerView rv;

    @Autowired(name = "teacherId")
    int teacherId;
    @Autowired(name = "chooseSubjectId")
    String chooseSubjectId;

    private List<StudentWaitDataBean.ObjBean> list = new ArrayList<>();
    private HomeAdapter homeAdapter;

    @Override
    protected void onCreateView() {

        ARouter.getInstance().inject(this);

        initTitle();
        initGif();

        //获取老师列表数据
        initWaitList(teacherId);

        initView();

        timer.start();

        ObserverManager.getInstance().add(this);
    }

    private void initWaitList(int teacherId) {

        HttpUtils.with(this)
                .addParam("requestType", "SELECT_TEACHER_ID")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("subject_id", chooseSubjectId)
                .addParam("teacher_id", teacherId)
                .execute(new HttpNormalCallBack<StudentWaitDataBean>() {
                    @Override
                    public void onSuccess(StudentWaitDataBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {

                                if (list.size() > 0) {
                                    list.clear();
                                }
                                list.addAll(result.getObj());
                                homeAdapter.notifyDataSetChanged();

                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }

                });


    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_studentconnectwait;
    }


    protected void initTitle() {
        NomalNavigationBar navigationBar = new
                NomalNavigationBar.Builder(this)
                .setTitle("我的提问")
                .setLeftClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        onUserExitWaiting();
                    }
                })
                .builder();

    }


    private void initView() {

        homeAdapter = new HomeAdapter(this, list);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(homeAdapter);

    }

    /**
     * 用户点击左上角与手机返回键想要退出提示
     */
    public void onUserExitWaiting() {

        CoachAIStudyDialog.getInstance()
                .setTitle("温馨提示")
                .setContent("因问题已有老师接收，退出等待暂压的兔币将不会退还给您，是否确定继续取消退出？")
                .setSureListener(new CoachAIStudyDialog.SurelListener() {
                    @Override
                    public void onSure() {

                        //学生取消提问，通知后台，删除本次数据
                        sendCancelQuestionToSerVice();
                    }
                })
                .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                    @Override
                    public void onCancel() {

                    }
                }).show(getSupportFragmentManager());
    }

    private void sendCancelQuestionToSerVice() {

        HttpUtils.with(this)
                .addParam("requestType", "STUDENT_CANCEL_QUESTION_AND_ANSWER")
                .addParam("quiz_or_live", 0)
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<StudentCancelQuestionBean>() {
                    @Override
                    public void onSuccess(StudentCancelQuestionBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            showToast("退出成功");
                            finish();
                        }
                    }

                    @Override
                    public void onError(String e) {
                        finish();
                    }
                });

    }

    /**
     * 点击键盘退出按键时，弹出提示框
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && KeyEvent.KEYCODE_BACK == keyCode) {

            onUserExitWaiting();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void initGif() {
        Glide.with(this).load(R.drawable.waiting).listener(new RequestListener() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                if (resource instanceof GifDrawable) {
                    //加载一次
                    ((GifDrawable) resource).setLoopCount(-1);
                }

                return false;
            }


        }).into(ivGif);
    }

    @Override
    public void observerUpData(String content) {

        if (StringUtil.isNotEmpty(content, true)) {
            //用户在推送弹出框点击了确认，将退出本界面
            if ("CloseWaitActivity".equals(content)) {
                finish();
            }
        }

    }


    private class HomeAdapter extends BaseAdapter<StudentWaitDataBean.ObjBean> {

        public HomeAdapter(Context context, List<StudentWaitDataBean.ObjBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_connect_wait;
//            return R.layout.item_ask_question_find;
        }

        @SuppressLint("ResourceAsColor")
        @Override
        protected void toBindViewHolder(ViewHolder holder, final int position, final List<StudentWaitDataBean.ObjBean> mData) {

            final StudentWaitDataBean.ObjBean objBean = mData.get(position);
            ImageView imageView = holder.getView(R.id.iv_head);
            if (StringUtil.isNotEmpty(objBean.getPhoto_url(), true)) {
                final String url = objBean.getPhoto_url();
                Glide.with(StudentConnectWaitActivity.this)
                        .load(url)
                        .apply(GlideConfig.getCircleOptions())
                        .into(imageView);
            }

            if (StringUtil.isNotEmpty(objBean.getUser_name(), true)) {
                holder.setText(R.id.tv_name, mData.get(position).getUser_name());
            }

            if (StringUtil.isNotEmpty(objBean.getUser_name(), true)) {
                holder.setText(R.id.tv_name, mData.get(position).getUser_name());
            }

            if (StringUtil.isNotEmpty(objBean.getUser_name(), true)) {
                holder.setText(R.id.tv_name, mData.get(position).getUser_name());
            }

            //判断倒计时是否结束
            holder.setOnClickListener(R.id.tv_see, new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if ("00:00".equals(timeString)) {
                        int teacherId = objBean.getId();

                        //发起申请老师请求
                        initWaitList(teacherId);
                        timer.start();

                    } else {
                        showToast("老师正在赶来的路上，再等等吧！");
                    }
                }
            });
        }
    }


    //-----------------------------------------------------------------------------记时器

    String timeString = "";
    CountDownTimer timer = new CountDownTimer(1000 * 60 * 3, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            timeString = TimeUtils.converLongTimeToStr(millisUntilFinished);
            tvCutTime.setText("请耐心等待:" + timeString);
        }

        @Override
        public void onFinish() {

            timeString = "00:00";
            tvCutTime.setText("老师已超时，可以选择下面的老师哦！");
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        ObserverManager.getInstance().remove(this);
    }
}
